/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package app.transitalarm;

import android.app.AlertDialog.Builder;

import android.content.Context;
import android.content.DialogInterface;

import android.preference.ListPreference;

import android.util.AttributeSet;

import app.transitalarm.view.DaysOfWeek;

public final class RepeatPreference extends ListPreference {
    private final boolean[] vals = new DaysOfWeek(0).getRepeatArr();
    private OnRepeatChangedObserver mOnRepeatChangedObserver;

    public interface OnRepeatChangedObserver {
        /** RepeatPrefrence calls this to get initial state */
        DaysOfWeek getDaysOfWeek();

        /** Called when this preference has changed */
        void onRepeatChanged(boolean[] vals);
    }

    public RepeatPreference(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    void setOnRepeatChangedObserver(final OnRepeatChangedObserver onRepeatChangedObserver) {
        mOnRepeatChangedObserver = onRepeatChangedObserver;
    }

    @Override
    protected void onDialogClosed(final boolean positiveResult) {
        if (positiveResult) {
            mOnRepeatChangedObserver.onRepeatChanged(vals);
        }
    }

    @Override
    protected void onPrepareDialogBuilder(final Builder builder) {
        final CharSequence[] entries = getEntries();
        final CharSequence[] entryValues = getEntryValues();

        if ((entries == null) || (entryValues == null)) {
            throw new IllegalStateException("RepeatPreference requires an entries array and an entryValues array.");
        }

        final boolean[] current = mOnRepeatChangedObserver.getDaysOfWeek().getRepeatArr();

        for (int i = 0; i < vals.length; i++) {
            if (i < current.length) {
                vals[i] = current[i];
            } else {
                vals[i] = false;
            }
        }

        builder.setMultiChoiceItems(entries, vals, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which, final boolean isChecked) {
                    vals[which] = isChecked;
                }
            });
    }
}
